import React from "react";
import ReactDOM from "react-dom";
import wx from "wx";
import AJAX from "../../lib/ajax";
import InfiniteScroll from "react-infinite-scroller";
import Rules from "../../lib/rules";
import Tools from "../../lib/tools";
import Toast from "../MyPackage/components/Toast";
import { addErrorListener } from "../../lib/handleError"
import weixinShare from "../../lib/weixinShare";

// import $ from "jquery";
require('../../lib/rem');
require('./SendingPackageChooseSite.less')
require('../../styles/common.less')
require('../../styles/resetWeui.less')
require('../../styles/lux.less')
//判断寄件类型（1: 服务站点寄件    2: 柜体寄件）
const sendType = Tools.getParams().send_type;

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isReady: false,     //是否加载页面
            actionSheetIsOpen: false,
            senderName: "",
            senderPhone: "",
            senderAddress: "",
            logisId: "",   //已选物流中心Id
            logisName: "",   //已选物流中心Name
            longitude: "",   //经度
            latitude: "",  //纬度
            current: 1, //当前页码
            loadCount: 1,    //加载次数
            site_count: 0,//附近物流中心count
            site_list: [],//附近物流中心list

        };
        this.switchSiteList = this.switchSiteList.bind(this)
        this.getReceiverInfo = this.getReceiverInfo.bind(this)  //获取输入框内容
        this.handleClearInfo = this.handleClearInfo.bind(this)  //清楚输入框内容
        this.handleGetSite = this.handleGetSite.bind(this)  //点击－－－获取附近物流中心
        this.getSitList = this.getSitList.bind(this)  //请求－－－获取附近物流中心
        this.handleSelectSite = this.handleSelectSite.bind(this)  //选择物流中心
        this.handleSubmit = this.handleSubmit.bind(this)  //选择物流中心
    }

    componentWillMount() {
        addErrorListener()()
        weixinShare.hideAll();
    }


    componentDidMount() {
        AJAX.appendBaiduAnalysis()

        var _this = this;

        //1: 服务站点寄件
        if (sendType == 1) {
            AJAX.request("get_signature", {
                full_url: window.location.href
            }, (data) => {
                wx.config({
                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: data.body.appid, // 必填，公众号的唯一标识
                    timestamp: data.body.timestamp, // 必填，生成签名的时间戳
                    nonceStr: data.body.noncestr, // 必填，生成签名的随机串
                    signature: data.body.signature,// 必填，签名，见附录1
                    jsApiList: ["getLocation"] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                })
                wx.ready(()=> {
                    wx.getLocation({
                        type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                        success: function (res) {
                            var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                            var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                            var speed = res.speed; // 速度，以米/每秒计
                            var accuracy = res.accuracy; // 位置精度

                            _this.setState({
                                isReady: true,     //是否加载页面
                                latitude: latitude,   //纬度
                                longitude: longitude,   //经度
                            })
                        }
                    });
                })

                //默认
                //设置寄件站点
                var logisInfo_x = JSON.parse(localStorage.getItem('logisInfo_x'));
                this.setState({
                    ogisId: logisInfo_x.id,   //已选物流中心Id
                    logisName: logisInfo_x.name,   //已选物流中心Name
                })
                //设置寄人信息
                var sender_addr_x = JSON.parse(localStorage.getItem('sender_addr_x'));

                if (sender_addr_x) {
                    _this.setState({
                        senderName: sender_addr_x.realname,
                        senderPhone: String(sender_addr_x.phone),
                        senderAddress: sender_addr_x.address,
                    })
                }
            })
        } else {
            //柜体寄件
            //设置寄人信息
            var sender_addr_x = JSON.parse(localStorage.getItem('cabinet_sender_addr_x'));

            this.setState({
                isReady: true,     //是否加载页面
            })
            if (sender_addr_x) {
                _this.setState({
                    senderName: sender_addr_x.realname,
                    senderPhone: String(sender_addr_x.phone),
                    senderAddress: sender_addr_x.address,
                })
            }
        }

    }

    //开关actionSheet
    switchSiteList(isOpen) {
        this.setState({
            actionSheetIsOpen: isOpen
        })
    }

    //获取输入框内容
    getReceiverInfo(type, e) {
        var value = String(e.target.value)
        this.setState({
            [type]: value
        })
        //将输入信息存入localStorage
        var storage = window.localStorage;
        storage[type] = e.target.value;
    }

    //清楚输入框内容
    handleClearInfo(type) {
        this.setState({
            [type]: ""
        })


    }

    //点击获取附近物流中心
    handleGetSite() {
        this.setState({
            current: 1, //当前页码
            loadCount: 1,    //加载次数
            site_count: 0,//附近物流中心count
            site_list: [],//附近物流中心list
        })
        this.getSitList()

    }

    //获取附近物流中心
    getSitList(current = 1) {
        var _this = this;
        this.setState({
            current: current,
        })
        //获取寄件人位置信息
        var location = JSON.parse(window.localStorage.sender_locationInfo_x);

        //如果首页没有获取到，取本页请求返回信息
        if (!location) {
            location.latitude = this.state.latitude;
            location.longitude = this.state.longitude;
        }

        AJAX.request("logis_near_list", {
            page: current,
            psize: 5,
            latitude: location.latitude,   //纬度 39.98393
            longitude: location.longitude,   //经度 116.4855
        }, (data) => {
            if (data.code == 0) {
                let myNearData = {
                    count: data.body.count,
                    list: data.body.list
                }
                _this.setState({
                    actionSheetIsOpen: true,
                    site_count: myNearData.count,
                    site_list: _this.state.site_list.concat(myNearData.list),
                    loadCount: Math.ceil(myNearData.count / 5)    //获取总页数（psize == 5）
                })
            }

        })
    }

    //选择物流中心－－－服务站点
    handleSelectSite(item) {
        this.setState({
            logisId: item.id,
            logisName: item.name,
            actionSheetIsOpen: false
        })
        //将信息存入localStorage
        var storage = window.localStorage;
        //物流中心信息
        storage.logisInfo_x = JSON.stringify(item);
    }

    //加载更多(物流中心－－－服务站点)
    loadMoreData(current) {
        // alert(current)
        var _current = current + 1;
        var _this = this;
        //判断加载次数
        if (this.state.loadCount) {
            if (_current < _this.state.loadCount || _current == _this.state.loadCount) {
                // alert("111！！！")
                _this.getSitList(_current)
            } else {
                // alert("没有数据了！！！")
            }
        }
    }


    //确定提交
    handleSubmit() {
        var sender_addr_x = {
            realname: this.state.senderName,
            phone: this.state.senderPhone,
            address: this.state.senderAddress,
        }

        //    验证手机号
        if (this.state.senderPhone.length == 0) {
            Toast.warn({
                content: '请输入联系方式'
            });
        } else if (!Rules.phone(this.state.senderPhone) && !Rules.officePhone(this.state.senderPhone)) {
            Toast.warn({
                content: '联系方式格式错误'
            });
            //    验证姓名
        } else if (this.state.senderName.length == 0) {
            Toast.warn({
                content: '请输入姓名'
            });
        } else if (!Rules.len(this.state.senderName, 2, 40)) {
            Toast.warn({
                content: '姓名格式错误'
            });
            //    验证地址
        } else if (this.state.senderAddress.length != 0 && !Rules.len(this.state.senderAddress, 1, 100)) {
            Toast.warn({
                content: '详细地址格式错误'
            });
        } else {
            // alert(JSON.stringify(sender_addr_x))
            //将信息存入localStorage
            var storage = window.localStorage;

            //判断寄件类型－跳转（1: 服务站点寄件   2:柜体寄件）
            //服务站点寄件
            if (sendType == 1) {
                //寄件人信息
                storage.sender_addr_x = JSON.stringify(sender_addr_x);
                window.location.href = "./SendingPackageHeader";

            } else if (sendType == 2) {
                //寄件人信息
                storage.cabinet_sender_addr_x = JSON.stringify(sender_addr_x);
                //柜体寄件
                window.location.href = "./CabinetSendingHeader";

            }
        }

    }

    render() {
        const loader = <div className="loader"></div>;
        const sendType = Tools.getParams().send_type;
        // console.log("actionSheetIsOpen: ",this.state.actionSheetIsOpen);
        var actionSheetClassName = this.state.actionSheetIsOpen ? " weui-actionsheet weui-actionsheet_toggle" : "weui-actionsheet";
        var maskClassName = this.state.actionSheetIsOpen ? " weui-mask" : "weui-mask none";

        return (
            this.state.isReady &&
            <div className="main">
                <div className="weui-cells weui-cells_form">
                    <div className="weui-cell">
                        <div className="weui-cell__hd"><label className="weui-label">姓名</label></div>
                        <div className="flex weui-cell__bd">
                            <input className="weui-input" value={this.state.senderName}
                                   onChange={this.getReceiverInfo.bind(this, "senderName")} required="required"
                                   autoComplete="autoComplete"
                                   placeholder="请填写真实姓名"/>
                            <i onClick={this.handleClearInfo.bind(this, "senderName")}
                               className="iconfont iconG icon-cuowu"></i>
                        </div>
                    </div>
                    <div className="weui-cell ">
                        <div className="weui-cell__hd">
                            <label className="weui-label">联系方式</label>
                        </div>
                        <div className="flex weui-cell__bd">
                            <input className="weui-input" value={this.state.senderPhone}
                                   onChange={this.getReceiverInfo.bind(this, "senderPhone")} required="required"
                                   autoComplete="autoComplete" type="tel"
                                   placeholder="请填写联系方式"/>
                            <i onClick={this.handleClearInfo.bind(this, "senderPhone")}
                               className="iconfont iconG icon-cuowu"></i>
                        </div>
                    </div>
                    {sendType == 1 && <div className="weui-cell">
                        <div className="weui-cell__hd">
                            <label className="weui-label">服务站点</label>
                        </div>
                        <div className="flex weui-cell__bd ">
                            <input className="weui-input" required="required" value={this.state.logisName}
                                   autoComplete="autoComplete"
                                   placeholder="请填写服务站点"/>
                            <i onClick={this.handleGetSite}
                               className="iconfont fontSize26px iconB icon-dingwei"></i>

                        </div>
                    </div>}

                    <div className="weui-cell">
                        <div className="weui-cell__hd"><label className="weui-label">详细地址</label></div>
                        <div className="flex weui-cell__bd">
                            <textarea className="weui-textarea" value={this.state.senderAddress}
                                      onChange={this.getReceiverInfo.bind(this, "senderAddress")}
                                      autoComplete="autoComplete" placeholder="选填"/>
                            <i onClick={this.handleClearInfo.bind(this, "senderAddress")}
                               className="iconfont iconG icon-cuowu"></i>
                        </div>
                    </div>
                </div>

                <div className="weui-btn-area">
                    <a className="weui-btn " href="javascript:;" id="showTooltips"
                       onClick={this.handleSubmit}
                    >确认</a>
                </div>

                <div>
                    <div className={maskClassName} id="iosMask" onClick={this.switchSiteList.bind(this, false)}></div>
                    <div className={actionSheetClassName} id="iosActionsheet">
                        <div className="weui-cells">
                            <div className="weui-cell">
                                <div className="weui-cell__bd">
                                    <p></p>
                                </div>
                                <div className="weui-cell__ft" onClick={this.switchSiteList.bind(this, false)}>
                                    <i className="iconfont iconG icon-cha"></i>
                                </div>
                            </div>
                        </div>
                        <div className="scroll-box">
                            <InfiniteScroll
                                initialLoad={false}
                                pageStart={0}
                                threshold={5}
                                loadMore={this.loadMoreData.bind(this, this.state.current)}
                                hasMore={true}
                                useWindow={false}
                                loader={loader}
                            >
                                <div className="weui-actionsheet__menu">
                                    {
                                        this.state.site_list.map(item => {
                                            return (
                                                <div className="weui-actionsheet__cell"
                                                     onClick={this.handleSelectSite.bind(this, item)}>
                                                    <p>{item.name}</p>
                                                    <p className="textG">{item.address}</p>
                                                </div>
                                            )
                                        })
                                    }
                                </div>

                            </InfiniteScroll>
                        </div>

                    </div>
                </div>
            </div>


        )
    }
}
ReactDOM.render(<App />, document.getElementById('app'));
if (module.hot) {
    module.hot.accept();
}